// services/paper.js
const db = wx.cloud.database();
const _ = db.command;

/**
 * 获取试卷列表
 * @param {Object} params 查询参数
 * @returns {Promise} 返回试卷列表
 */
async function getPaperList(params = {}) {
  try {
    const { subject, status, keyword, page = 1, size = 10 } = params;
    
    // 构建查询条件
    const query = {};
    if (subject) query.subject = subject;
    if (status) query.status = status;
    if (keyword) {
      query.title = db.RegExp({
        regexp: keyword,
        options: 'i'
      });
    }
    
    // 获取总数
    const countResult = await db.collection('papers').where(query).count();
    const total = countResult.total;
    
    // 获取列表数据
    const listResult = await db.collection('papers')
      .where(query)
      .skip((page - 1) * size)
      .limit(size)
      .orderBy('createTime', 'desc')
      .get();
    
    return {
      success: true,
      data: {
        list: listResult.data,
        total
      }
    };
  } catch (error) {
    console.error('获取试卷列表失败', error);
    return {
      success: false,
      message: '获取试卷列表失败'
    };
  }
}

/**
 * 获取试卷详情
 * @param {string} paperId 试卷ID
 * @returns {Promise} 返回试卷详情
 */
async function getPaperDetail(paperId) {
  try {
    const result = await db.collection('papers').doc(paperId).get();
    return {
      success: true,
      data: result.data
    };
  } catch (error) {
    console.error('获取试卷详情失败', error);
    return {
      success: false,
      message: '获取试卷详情失败'
    };
  }
}

/**
 * 创建试卷
 * @param {Object} paper 试卷数据
 * @returns {Promise} 返回创建结果
 */
async function createPaper(paper) {
  try {
    const now = new Date();
    const data = {
      ...paper,
      createTime: now,
      updateTime: now,
      status: '未发布'
    };
    
    // 计算总分
    if (data.questions && data.questions.length > 0) {
      data.totalScore = data.questions.reduce((sum, q) => sum + (q.score || 0), 0);
    } else {
      data.totalScore = 0;
    }
    
    const result = await db.collection('papers').add({ data });
    return {
      success: true,
      data: {
        _id: result._id
      }
    };
  } catch (error) {
    console.error('创建试卷失败', error);
    return {
      success: false,
      message: '创建试卷失败'
    };
  }
}

/**
 * 更新试卷
 * @param {string} paperId 试卷ID
 * @param {Object} data 更新数据
 * @returns {Promise} 返回更新结果
 */
async function updatePaper(paperId, data) {
  try {
    const now = new Date();
    const updateData = {
      ...data,
      updateTime: now
    };
    
    // 如果更新了试题，重新计算总分
    if (data.questions) {
      updateData.totalScore = data.questions.reduce((sum, q) => sum + (q.score || 0), 0);
    }
    
    await db.collection('papers').doc(paperId).update({
      data: updateData
    });
    
    return {
      success: true
    };
  } catch (error) {
    console.error('更新试卷失败', error);
    return {
      success: false,
      message: '更新试卷失败'
    };
  }
}

/**
 * 删除试卷
 * @param {string} paperId 试卷ID
 * @returns {Promise} 返回删除结果
 */
async function deletePaper(paperId) {
  try {
    await db.collection('papers').doc(paperId).remove();
    return {
      success: true
    };
  } catch (error) {
    console.error('删除试卷失败', error);
    return {
      success: false,
      message: '删除试卷失败'
    };
  }
}

/**
 * 发布试卷
 * @param {string} paperId 试卷ID
 * @returns {Promise} 返回发布结果
 */
async function publishPaper(paperId) {
  try {
    await db.collection('papers').doc(paperId).update({
      data: {
        status: '已发布',
        updateTime: new Date()
      }
    });
    
    return {
      success: true
    };
  } catch (error) {
    console.error('发布试卷失败', error);
    return {
      success: false,
      message: '发布试卷失败'
    };
  }
}

module.exports = {
  getPaperList,
  getPaperDetail,
  createPaper,
  updatePaper,
  deletePaper,
  publishPaper
}; 